import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key,required this.userInfo});
  final Map<String, dynamic> userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final TextEditingController _nickNameController = TextEditingController();
  Widget getAvatar(){
    if (widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != ''){
      // 判断是以/data开头
      if (widget.userInfo['avatar'].startsWith('/data')){
        return Image.file(
          File(widget.userInfo['avatar']),
          width: 30,
          height: 30,
        );
      }
      return Image.network(
        widget.userInfo['avatar'],
        width: 30,
        height: 30,
      );
    }
    return Image.asset(
      'assets/images/avatar_2.jpg',
      width: 30,
      height: 30,
    );
  }
  // 是否选择图片
  bool isSelected = false;
  // 是否在上传中
  bool isUploading = false;
  // 文件名称
  String fileName = '';

  // 从本地选择图片
  _selectImage() async {
    // 创建实例
    final ImagePicker picker = ImagePicker();
    // 从本地选择一张图片
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      isSelected = true;
      // 赋值图片名称
      // image是一个blob临时地址
      fileName = image.name;
      PromptAction.showToast('选择图片成功');
      setState(() {
        widget.userInfo['avatar'] = image.path;
      });
      Navigator.pop(context);
    }
  }
  // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            width: double.infinity,
            height: 180,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: GestureDetector(
                    onTap: () {
                      _selectImage();
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.photo_album),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "相册",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cancel_outlined),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "取消",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }
  // @override
  // void initState() {
  //   super.initState();
  //   if (widget.userInfo['nickName'] != null && widget.userInfo['nickName'] != ''){
  //     _nickNameController.text = widget.userInfo['nickName'];
  //   }
  // }
  // 保存用户信息
  void _saveUserInfo() async{
    if (_nickNameController.text.isEmpty){
      PromptAction.showErrorToast('请输入昵称');
      return;
    }
    RegExp reg = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if (!reg.hasMatch(_nickNameController.text)){
      PromptAction.showErrorToast('昵称格式不正确');
    }
    if (!isUploading){
      // 此时可以上传
      isUploading = true;
      if (isSelected){
        // 转为formdata对象
        FormData formData = FormData.fromMap({
          // file需要上传的是二进制的数据，所以使用MultipartFile.fromBytes转为二进制
          'file':MultipartFile.fromBytes(
            // 参数是blob类型，使用readAsBytes转为了字节
            await XFile(widget.userInfo['avatar']).readAsBytes(),
            // 让文件名
            filename: fileName,
            // 文件类型
            // contentType: DioMediaType('image', 'jpg'),
          ),
          "type":'avatar'
        });
        final res = await uploadImageApi(formData);
        setState(() {
          widget.userInfo['avatar'] = res['url'];
        });
        
      }
      await updateUserInfoApi({
        'nickName': _nickNameController.text,
        'avatar': widget.userInfo['avatar'],
      });
      isUploading = false;
      isSelected = false;
      PromptAction.showSuccessToast('修改昵称成功');
      eventBus.fire(logSuccessEvent());
    }else {
        PromptAction.showToast('正在上传中……');
    }

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                GestureDetector(
                  // 可以让我们点击间距时，可以有效，如果不加，点了是没用的
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    _showAvatarDialog();
                  },
                  child: Row(
                  children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getAvatar(),
                      ),
                      const Icon(Icons.arrow_forward_ios, size: 12)
                    ],
                  )
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
